package com.hxtec.polaris.service.impl;

import com.hxtec.polaris.commons.api.vo.Result;
import com.hxtec.polaris.commons.constant.Code;
import com.hxtec.polaris.commons.constant.Log;
import com.hxtec.polaris.commons.constant.Msg;
import com.hxtec.polaris.commons.exception.MyException;
import com.hxtec.polaris.entity.ShopAddress;
import com.hxtec.polaris.mapper.ShopAddressMapper;
import com.hxtec.polaris.service.LocationService;
import com.hxtec.polaris.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Describtion 地址相关service
 * @Author yonyong
 * @Date 2019/12/3 15:32
 * @Version 1.0.0
 **/
@Service
@Transactional
public class LocationServiceImpl implements LocationService {

    private final static Logger logger = LoggerFactory.getLogger(LocationServiceImpl.class);
    private final static String LOG_CLASS_NAME = "LocationServiceImpl";
    private final static String LOG_METHOD_ADD_LOCATION = "addLoaction";
    private final static String LOG_METHOD_DEL_LOCATION = "deleteLoaction";
    private final static String LOG_METHOD_UPDATE_LOCATION ="updateLoaction";

    @Resource
    private ShopAddressMapper shopAddressMapper;
    @Resource
    private UserService userService;

    @Override
    public Object getLoaction() {
        List<Map<String,Object>> mapList = shopAddressMapper.getLocationByUsername(String.valueOf(userService.getUserInfo().getId()));
        if (mapList.size()>0){
            return Result.ok(mapList);
        }else {
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_QUERY_NULL));
        }
    }

    @Override
    public Object addLoaction(ShopAddress shopAddress) {
        try {
            doInsert(shopAddress);
        }catch (Exception e){
            String params = "shopAddress="+shopAddress.toString();
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.INSERT,LOG_CLASS_NAME,LOG_METHOD_ADD_LOCATION,params);
            throw new MyException(Result.error(Code.FAIL_4501,Msg.COMMON_FAIL),LOG_MSG);
        }
        return Result.ok(Msg.COMMON_OK);
    }

    @Override
    public Object updateLoaction(ShopAddress shopAddress) {
        try {
            doUpdate(shopAddress);
        }catch (Exception e){
            String params = "shopAddress="+shopAddress.toString();
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.UPDATE,LOG_CLASS_NAME,LOG_METHOD_UPDATE_LOCATION,params);
            throw new MyException(Result.error(Code.FAIL_4501,Msg.COMMON_FAIL),LOG_MSG);
        }
        return Result.ok(Msg.COMMON_OK);
    }

    @Override
    public Object deleteLoaction(List<String> ids) {
        try {
            doDelete(ids);
        }catch (Exception e){
            String params = "ids="+ids;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.DELETE,LOG_CLASS_NAME,LOG_METHOD_DEL_LOCATION,params);
            throw new MyException(Result.error(Code.FAIL_4501,Msg.COMMON_FAIL),LOG_MSG);
        }
        return Result.ok(Msg.COMMON_OK);
    }

    @Override
    public Object getDefaultLocation() {
        Map<String,Object> map = new HashMap<>(16);
        try {
            int count = shopAddressMapper.selectDefaultCountByUsername(userService.getUserPhonenumber());
            if (count > 0){
                map = shopAddressMapper.selectDefaultByUsername(userService.getUserPhonenumber());
            }else {
                //没有设置默认地址默认取最新一条作为订单展示的收货地址
                map = shopAddressMapper.getDefaultWhenNoDefaultByUsername(userService.getUserPhonenumber());
            }
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501,Msg.COMMON_QUERY_NULL));
        }
        return Result.ok(map);
    }

    @Override
    public Object checkLocation(ShopAddress shopAddress) {
        try{
            int count = shopAddressMapper.getLocationCountByIdAndUserName(shopAddress.getId(),userService.getUserPhonenumber());
            if (count>0){
                //如果数据库中有该id，以防被编辑，从数据库中查出该记录到页面展示
                Map<String,Object> map = shopAddressMapper.getLocationByIdAndUserName(shopAddress.getId(),userService.getUserPhonenumber());
                return Result.ok(map);
            }else {
                //如果数据库中没有该id则证明已被删除，展示最新的一条
                return getDefaultLocation();
            }
        }catch (Exception e){
            throw new MyException(Result.error(Code.FAIL_4501,Msg.COMMON_QUERY_NULL));
        }
    }

    /**
     * 执行添加收货地址业务
     * @param shopAddress
     */
    private void doInsert(ShopAddress shopAddress) {
        //查询数据库中当前用户设置了几条收货地址，如果是第一次添加收货地址，则该地址为默认收货地址
        String userId = String.valueOf(userService.getUserInfo().getId());
        shopAddress.setUserId(userId);
        shopAddress.setCreateTime(new Date());
        shopAddress.setUpdateTime(new Date());
        shopAddressMapper.insertLocation(shopAddress);

        //修正默认状态
        updateDefaultAddress(shopAddress);
    }

    /**
     * 执行更新收货地址业务
     * @param shopAddress
     */
    private void doUpdate(ShopAddress shopAddress) {
        shopAddress.setUpdateTime(new Date());
        shopAddressMapper.updateLocation(shopAddress);

        //修正默认状态
        updateDefaultAddress(shopAddress);
    }

    /**
     * 执行删除收货地址业务
     * @param ids
     */
    private void doDelete(List<String> ids) {
        for (String id: ids) {
            shopAddressMapper.deleteLocation(id);
        }
    }

    /**
     * 如果当前操作的的收货地址状态为默认的，则将当前用户的其他地址状态改为非默认，改为0
     * @param shopAddress
     */
    private void updateDefaultAddress(ShopAddress shopAddress){
        String userId = String.valueOf(userService.getUserInfo().getId());
        if (null != shopAddress.getWeight() && shopAddress.getWeight() == 1){
            shopAddressMapper.updateDefaultLocation(userId,shopAddress.getId());
        }
    }
}
